import { ClientRequest, net } from 'electron';
import { store } from '../../store';

/**
 * 请求工具类
 *
 * @author chitanda
 * @date 2022-06-09 16:06:22
 * @export
 * @class Http
 */
export class Http {

  /**
   * 发送 Post 请求
   *
   * @author chitanda
   * @date 2022-06-09 16:06:11
   * @static
   * @param {string} url
   * @param {Record<string, unknown>} data
   * @param {Record<string, string>} [headers]
   * @return {*}  {Promise<any>}
   */
  static post(url: string, data: Record<string, unknown>, headers?: Record<string, string>): Promise<any> {
    return new Promise((resolve, reject) => {
      const request = net.request({
        method: 'POST',
        url,
      });
      this.attachHeaders(request, {
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': `Basic ${store.get('token')}`,
      });
      if (headers) {
        this.attachHeaders(request, headers);
      }
      this.attachData(request, data);
      request.on('response', (response) => {
        response.on('data', (chunk) => {
          if (response.statusCode === 200) {
            resolve(JSON.parse(chunk.toString('utf-8')));
          } else {
            reject(chunk.toString('utf-8'));
          }
        });
      });
      request.on('error', reject);
      request.end();
    });
  }

  /**
   * 格式化请求数据
   *
   * @author chitanda
   * @date 2022-06-09 16:06:47
   * @protected
   * @static
   * @param {Record<string, unknown>} [opt={}]
   * @return {*}  {string}
   */
  protected static transformationPrams(opt: Record<string, unknown> = {}): string {
    const postData: string[] = [];
    const keys: string[] = Object.keys(opt);
    keys.forEach((key: string) => {
      const val = opt[key];
      if (val !== undefined && val !== null) {
        if (val instanceof Array || val instanceof Object) {
          postData.push(`${key}=${encodeURIComponent(JSON.stringify(val))}`);
        } else if (typeof val === 'string') {
          postData.push(`${key}=${encodeURIComponent(val)}`);
        } else {
          postData.push(`${key}=${val}`);
        }
      }
    });
    return postData.join('&');
  }

  /**
   * 附加请求头
   *
   * @author chitanda
   * @date 2022-06-09 16:06:23
   * @protected
   * @static
   * @param {ClientRequest} request
   * @param {Record<string, string>} headers
   */
  protected static attachHeaders(request: ClientRequest, headers: Record<string, string>): void {
    if (headers) {
      Object.keys(headers).forEach((key) => {
        request.setHeader(key, headers[key]);
      });
    }
  }

  /**
   * 附加请求数据
   *
   * @author chitanda
   * @date 2022-06-09 16:06:20
   * @protected
   * @static
   * @param {ClientRequest} request
   * @param {Record<string, unknown>} data
   */
  protected static attachData(request: ClientRequest, data: Record<string, unknown>): void {
    if (data) {
      request.write(JSON.stringify(data));
    }
  }
}
